package Army;

import Army.task.TaskLocate;
import Army.task.TaskDetroy;
import Army.task.TaskBuild;
import Army.unit.Unit;
import Army.BuildingAndUnit.Type;
import Component.MyPanel;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 *
 * @author Alvis
 */
public class Group {

	List<BuildingAndUnit> listUnit;
	boolean isSelected;

	public List<BuildingAndUnit> getListUnit() {
		return listUnit;
	}
	private BuildingAndUnit.Type groupType;

	public Type getGroupType() {
		return groupType;
	}

	public Group() {
		listUnit = new ArrayList<>();
		isSelected = true;
		groupType = BuildingAndUnit.Type.Null;
	}

	public Group(boolean select) {
		listUnit = new ArrayList<>();
		isSelected = select;
		groupType = BuildingAndUnit.Type.Null;
	}

	public void add(BuildingAndUnit unit) {
		listUnit.add(unit);
		
		if (groupType == BuildingAndUnit.Type.Null) {
			groupType = unit.getType();
		} else if (groupType != unit.getType()) {
			groupType = BuildingAndUnit.Type.BuildingAndUnit;
		}

		if (isSelected) {
			unit.select();
		}

	}
	public boolean isUnit()
	{
		for (BuildingAndUnit buildingAndUnit : listUnit) {
			if(buildingAndUnit.isBuilding()) {
				return false;
			}
		}
		return !listUnit.isEmpty();
	}

	public boolean isEmpty() {
		return listUnit.isEmpty();
	}

	public Iterator<BuildingAndUnit> iterator() {
		return listUnit.iterator();
	}

	public void clear() {

		groupType = BuildingAndUnit.Type.Null;
		for (Iterator<BuildingAndUnit> it = listUnit.iterator(); it.hasNext();) {
			BuildingAndUnit unit = it.next();
			unit.disSelect();
			it.remove();
		}

	}

	public int size() {
		return listUnit.size();
	}

	public void setTarget(Point pos) {
		int i = 0;
		if (listUnit.isEmpty()) {
			return;
		}

		double r = Unit.getAngle(listUnit.get(0).getPosition(), pos);
		int n = listUnit.size();
		int a = 3 * (int) (Math.sqrt(n / 3) + 0.5);
		if (a == 0) {
			a = 1;
		}
		for (Iterator<BuildingAndUnit> it = listUnit.iterator(); it.hasNext();) {
			BuildingAndUnit unit = it.next();
			Point p = new Point(pos);
			double x = (i % a - (double)a / 2) * 50;
			double y = (i / a - (double)a / 6) * 50;
			p.x += -Math.sin(r)*y + Math.cos(r)*x;
			p.y += Math.sin(r)*x + Math.cos(r)*y;
			
			i++;

			unit.setTask(new TaskLocate(unit, p));

		}
	}

	public void setTarget(BuildingAndUnit army) {
		for (Iterator<BuildingAndUnit> it = listUnit.iterator(); it.hasNext();) {
			BuildingAndUnit unit = it.next();
			//unit.setTarget(army);
			if (groupType == BuildingAndUnit.Type.UnitWorker) {
				unit.setTask(new TaskBuild(unit, army));
			} else {
				unit.setTask(new TaskDetroy(unit, army));
			}
		}
	}

	public void remove(Unit unit) {
	}

	public MyPanel generatePanel(int x, int y) {
		MyPanel panel = new MyPanel(null, x, y);

		return panel;
	}
}
